package com.my9yu.common.socket.client;

import java.net.InetSocketAddress;
import java.net.SocketAddress;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.future.ReadFuture;
import org.apache.mina.core.future.WriteFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import com.my9yu.common.socket.codec.json.JsonCodecFactory;

public class Client {

	public Object send(Object body) {

		ClientHander clientHander = new ClientHander();
		NioSocketConnector connector = new NioSocketConnector();

		connector.setHandler(clientHander);

		SocketAddress severAddress = new InetSocketAddress("127.0.0.1", 22222);

		connector.connect(severAddress);

		connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new JsonCodecFactory()));

		ConnectFuture future = connector.connect(severAddress);
		future.awaitUninterruptibly();
		IoSession session = future.getSession();

		session.getConfig().setUseReadOperation(true);

		ReadFuture readFuture = session.read();

		WriteFuture writeFuture = session.write(body);

		writeFuture.awaitUninterruptibly();

		readFuture.awaitUninterruptibly();
		Object result = readFuture.getMessage();

		return result;

	}

}
